package com.starmark.sys.login.provider.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.starmark.core.framework.base.AbstractController;
import com.starmark.core.framework.response.ErrorResponseData;
import com.starmark.core.framework.response.Response;
import com.starmark.core.framework.response.SuccessResponseData;
import com.starmark.core.framework.util.RedisUtils;
import com.starmark.gateway.auth.api.service.IAuthApiService;
import com.starmark.sys.login.api.dto.LoginDto;
import com.starmark.sys.login.api.dto.UserInfoDto;
import com.starmark.sys.login.api.dto.UserLoginToken;
import com.starmark.sys.login.provider.service.ICaptchaService;
import com.starmark.sys.login.provider.service.SysLoginServiceFactory;
import com.starmark.sys.login.provider.util.JWTService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * @author starmark
 * @create 2020-01-18 22:18
 */
@RestController
@Api(
        value = "系统登陆",
        description = "系统登陆"
)
@RequestMapping(value = "/sys/login")
public class LoginController extends AbstractController {

    private static final String STARMARK_GATEWAY_PROJECT = "starmark:gateway:project:info:";
    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private SysLoginServiceFactory loginServiceFactory;


    @Resource
    private IAuthApiService authApiService;

    @Resource
    private JWTService jwtService;

    @Autowired
    private ICaptchaService captchaService;

    /**
     * 登录方法
     *
     * @param loginDto 登陆对象
     * @return 登陆结果
     */
    @ApiOperation(value = "登陆")
    @RequestMapping(
            value = "/loginSystem",
            method = RequestMethod.POST
    )
    public Response loginSystem(@RequestBody LoginDto loginDto) {
        Assert.hasText(loginDto.getId(), "请求ID不允许为空");
        Assert.hasText(loginDto.getRightCode(), "验证码不允许为空");
        int checkResult = captchaService.checkCaptcha(loginDto.getId(), loginDto.getRightCode());
        if (checkResult == -1 || checkResult == 1) {
            return ErrorResponseData.newInstance("验证码不正确或已过期");

        }
        SuccessResponseData successResponse = new SuccessResponseData();

        UserLoginToken token = UserLoginToken.buildPassword(loginDto.getUsername(), loginDto.getPassword(), "default");
        UserInfoDto userInfoDto = loginServiceFactory.login(token);
        //获取相关权限
        userInfoDto.setRoles(authApiService.getRoleIdsByOrgId(Collections.singletonList(userInfoDto.getId()), loginDto.getSystemCode()));
        userInfoDto.setAdmin(authApiService.isAdmin(userInfoDto.getId(), loginDto.getSystemCode()));
        userInfoDto.setProjectCode(loginDto.getSystemCode());
        successResponse.setMsg("登录成功");
        JSONObject jsonObject = this.getProjectInfo(loginDto.getSystemCode());

        successResponse.setData(jwtService.sign(JSON.toJSONString(userInfoDto), jsonObject.getString("salt"),
                jsonObject.getLongValue("expireTime")));

        return successResponse;
    }

    /**
     * 2、生成验证码
     *
     * @param id                  请求ID
     * @param httpServletResponse 响应
     * @throws IOException 生成验证码异常
     */
    @RequestMapping("/createCaptcha")
    public void createCaptcha(@RequestParam("id") String id, HttpServletResponse httpServletResponse) throws IOException {
        Assert.hasText(id, "请求ID不允许为空");
        captchaService.createCaptcha(id, httpServletResponse);
    }

    /**
     * 3、校对验证码
     *
     * @param id 请求ID
     * @param rightCode 验证码ID
     * @return 请求结果
     */
    @RequestMapping("/checkCaptcha")
    public Response checkCaptcha(@RequestParam("id") String id, @RequestParam("rightCode") String rightCode) {
        Assert.hasText(id, "请求ID不允许为空");
        Assert.hasText(rightCode, "验证码不允许为空");
        int checkResult = captchaService.checkCaptcha(id, rightCode);
        if (checkResult == -1 || checkResult == 1) {
            return ErrorResponseData.newInstance("验证码不正确或已过期");

        }
        return SuccessResponseData.newInstance();
    }

    private JSONObject getProjectInfo(String projectCode) {
        String projectInfo = (String) redisUtils.get(STARMARK_GATEWAY_PROJECT + projectCode);
        return JSON.parseObject(projectInfo);

    }


    @ApiOperation(value = "登出")
    @GetMapping("/logout")
    public void logout() {
        //Subject currentUser = SecurityUtils.getSubject();

        // currentUser.logout();
    }


}



